package com.ljsw.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.hdhe.uhf.main.SaomiaoUtil;
import com.android.hdhe.uhf.main.Util;
import com.android.hdhe.uhf.reader.CaseString;
import com.android.hdhe.uhf.reader.UhfReader;
import com.bumptech.glide.Glide;
import com.ljsw.activity.BigMapActivity;
import com.ljsw.activity.R;
import com.ljsw.adapter.PaiZhaoAdapter;
import com.ljsw.adapter.ZhouZhuanAdapter;
import com.ljsw.application.App;
import com.ljsw.dialog.DeleteDialog;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.ProgressBarDialog;
import com.ljsw.dialog.SubmitDialog;
import com.ljsw.dialog.SuccessDialog;
import com.ljsw.dialog.UserLoginDialog;
import com.ljsw.dialog.WritePadDialog;
import com.ljsw.entity.Emp;
import com.ljsw.entity.Person;
import com.ljsw.entity.RenWuClass;
import com.ljsw.entity.User;
import com.ljsw.server.UpServer;
import com.ljsw.util.BitmapUtil;
import com.ljsw.util.Constant;
import com.ljsw.util.DecodeLock;
import com.ljsw.util.DialogListener;
import com.ljsw.util.DialogManager;
import com.ljsw.util.FingerUtil.OnGetFingerListener;
import com.ljsw.util.MD5;
import com.ljsw.util.ShowToastUtils;
import com.ljsw.util.Skip;
import com.ljsw.view.PaizhaoGridView;
import com.poka.device.RFIDDevice;
import com.poka.embedextract.FileOperation;
import com.poka.entity.ReciveList;
import com.poka_global_constant.GlobalConstant;

import java.io.File;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Environment.getExternalStorageDirectory;

/**
 * 我的任务 开始扫描视图 作者: 石锚 版本: 1.0 日期: 2015-10-16  12 /2 更改
 */
//
@SuppressLint("HandlerLeak")
public class KssmFragment extends BaseFragment implements OnClickListener,
        OnItemClickListener, OnItemLongClickListener, OnGetFingerListener {
    private static final String TAG = "KssmFragment押运";


    private String leftName, rightName;// 左签名和右签名
    private DialogManager dmanager;// 弹出框管理类
    private SuccessDialog successDialog;// 成功弹出框
    private SubmitDialog subDialog;// 提交弹出框
    private LoginDialog dialog;// 获取任务Dialog
    private LoginDialog lockdialog;//  开关锁dialog

    private ProgressBarDialog progressDialog;// 进度条弹出框
    private DeleteDialog deleteDialog;// 删除弹出框
    private RenWuClass rw;// 我的任务封装类
    private View view;
    private ArrayList<String> list = new ArrayList<String>();// 要扫描的集合数据
    private ArrayList<String> listzou = new ArrayList<String>();//周转箱号放入集合
    private ArrayList<String> arrayListzhou = new ArrayList<String>(); //存放传过来的箱子号
    private List<Person> plist = new ArrayList<Person>();// 企业人员集合 其实就2个
    private PaiZhaoAdapter paiZhaoAdapter;// 我的任务 开始拍照 适配器
    private PaizhaoGridView gridView;// 开始拍照列表
    private TextView back;// 返回按钮

    private TextView zzxclear;// 清空周转箱，重扫

    private TextView startsaomiao,// 开始扫描
            startpaizhao,// 开始拍照
            startjiaojie,// 开始交接
            qrwanceng,// 确认完成
            zzx_queren;// 扫描确认按钮
    private TextView tv_sign1, tv_sign2;// 签名提示
    private ImageView iv_sign1, iv_sign2;// 签名图片
    // ArrayList<Bitmap> photoPaths = new ArrayList<Bitmap>(); // 保存拍照相片的集合
    private String strPath; // 拍照后相片保存的绝对路径
    private List<String> pathlist = new ArrayList<String>();// 图片路径集合
    private List<String> namelist = new ArrayList<String>();// 图片名集合
    private ArrayList<String> photoPaths = new ArrayList<String>();// 图片名集合
    private Bundle bundle;
    private int imageNum = 0;// 上传图片的数量

    private LinearLayout zzxlist_layout,// 填充器（美化UI,周转箱）
            zzxlist_layout_view,// 填充器（周转箱列表）
            zzxlist_check,// 核对布局（重扫，确认）
            qianmingLayout;// 签名人员布局

    private LinearLayout banfengbao, quanfengbao;// 半封包，全封包
    private TextView tv_sign3, tv_sign4;// 半封包名字
    private ImageView iv_sign3, iv_sign4;// 半封包名字

    private TextView tv_sign5;// 全封包名字
    private ImageView iv_sign5;// 全封包名字

    private FragmentManager fm;
    private String cid;// 车牌号
    private boolean tflag = true;// 控制扫描的标识

    private String fristUserId = null;// 用户登录的密码
    private boolean uflag = true;// 标识是否是第一个人登录标识
    private File file;
    // 提交的参数
    private String userid;// 全封包： useid:押运员 半封包： useid:上门人员
    private int fengbaostate; // 封包状态
    private String qiyeyuan = ""; // 企业人员id
    private String paigongdan;// 派工单
    private String zhouzhuangxiang = "";// 周转箱
    private String fileNamelist = "";// 图片名称集合（要拼接）
    private int flag = 1;// 1.标识上传图片 2.标识提交数据
    private UhfReader reader; // 超高频读写器
    private SaomiaoUtil saomiao;
    private UserLoginDialog useDialog;
    private String userId;// 用户登录的账号
    private String pwd;// 用户登录的密码
    private User user;// 登录用户
    App app;
    private String jigouId; // 上门人员机构Id
    private List<Emp> userList; // 上门人员
    public final static int KSSM_TAG = 3;
    private String embed = "";// 水印内容
    FileOperation operation = new FileOperation();
    private String embedPath = "";
    //    private FingerUtil mFingerUtil;// 指纹验证工具类
    private int times = 0;// 验证失败超过3次弹出窗口
    private boolean threeTimes = false;// 失败累计三次
    /*
     * 为密码锁功能所添加的变量声明
     * @author zhouKai
     */
    private RadioGroup rg_zzx_num; // 周转箱编号单选组
    private Button btn_lock_zzx; // 闭锁
    private Button btn_unLock_zzx;  // 开锁
    private DecodeLock decodeLock; // 密码锁对象
    private TextView tvsuohao;
    private String kssrb;

    /*
     *上传签名文件txt
     *modify by wangmeng 2017-12-12
     *
     */
    private List<String> txtPathList = new ArrayList<String>();//txt文件路径集合
    private List<String> txtNamelist = new ArrayList<String>();// txt文件名集合
    private Map<String, String> signInfo = new HashMap<String, String>();
    private String signTitle = "";//现场照片和对应txt文件的名称


    private String selenumber; //用于存放扫描到的锁号码
    private ListView listviewlocknumber;
    private ZhouZhuanAdapter zZhouzhuanadapter;


//开新锁的代码

    /**
     * Id to identity READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{"foo@example.com:hello", "bar@example.com:world"};
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */

    private RFIDDevice rfidDevice;
    private ReciveList receivelist;
    private String selectItem = "";

    private final int OPEN_LOCK = 1;
    private final int CLOSE_LOCK = 0;

    private RFIDDevice.OnDataReceiveListener listener = null;
    private String operator = null;
    ArrayList<String> LockID = new ArrayList<String>();//c存放锁号码


    private Handler handlerzhuan;
    private Handler handlerzhuannum;
    private int chongsao;
    Long LastClickTime;
    ShowToastUtils showToastUtils = new ShowToastUtils();

    @SuppressWarnings("unchecked")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        view = inflater.inflate(R.layout.fragmnet_kssm, container, false);


        app = (App) getActivity().getApplication();
        fm = getFragmentManager();
        // 获取读写器实例，若返回Null,则串口初始化失败
        reader = UhfReader.getInstance();
        Util.initSoundPool(getActivity());// 初始化扫描的声音
        saomiao = new SaomiaoUtil(reader);// 创建扫描工具类
        /** 初始化弹出框 */
        dmanager = new DialogManager(getActivity());
        useDialog = dmanager.getUserLoginDialog();
        progressDialog = dmanager.getProgressBarDialog();
        dialog = dmanager.getLoginDialog();
        subDialog = dmanager.getSubmitDialog();
        deleteDialog = dmanager.getDeleteDialog();
        successDialog = dmanager.getSuccessDialog();
        bundle = getArguments();
        if (bundle != null) {// 获取上个页面传过来的值
            rw = (RenWuClass) bundle.getSerializable("rw");
            cid = bundle.getString("cid");// 车牌号
            plist = (List<Person>) bundle.getSerializable("plist");
            userList = (List<Emp>) bundle.getSerializable("userList");
            fengbaostate = Integer.parseInt(rw.getType().trim());// 转化封包状态
            if (fengbaostate == 0) {
                try {
                    jigouId = userList.get(0).getJigouId();
                } catch (Exception e) {
                    new AlertDialog.Builder(getActivity()).setMessage(
                            "机构ID异常" + jigouId).show();
                }
            }
        }
        receivelist = new ReciveList();
        initView();
        saomiao.setHandler(handler);
        useDialog.setmHandler(handler);
        loadData();
        return view;

    }


    private void loadData() {

        DownIimage();
//        final String newPic = getExternalStorageDirectory().toString() + "/images/"+"white1" + ".jpg";
        final String newPic1 = getExternalStorageDirectory().toString() +"/images/"+ "white1" + ".jpg";
//        Log.d(TAG, "!!!!!" + newPic);
        KssmFragment.this.getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {//white1.jpg
                namelist.add("white1" + ".jpg");
//                pathlist.add(newPic);
                photoPaths.add(newPic1);
//                photoPaths.add(newPic);
//                photoPaths.add("https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87%E5%94%AF%E7%BE%8E%20%E5%8F%A4%E8%A3%85&step_word=&hs=2&pn=4&spn=0&di=128370&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=2625491414%2C4048582725&os=1947748745%2C2191795669&simid=4233046544%2C809518434&adpicid=0&lpn=0&ln=1241&fr=&fmq=1389861203899_R&fm=&ic=0&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&oriquery=%E5%9B%BE%E7%89%87%E5%94%AF%E7%BE%8E&objurl=http%3A%2F%2Fimage.namedq.com%2Fuploads%2F20191215%2F18%2F1576404670-DIGgnHzcpw.jpg&gsm=1e&rpstart=0&rpnum=0&islist=&querylist=&force=undefined");
//                photoPaths.add("https://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87%E5%94%AF%E7%BE%8E%20%E5%8F%A4%E8%A3%85&step_word=&hs=2&pn=13&spn=0&di=50270&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=94782098%2C1643911844&os=3165904618%2C4178241826&simid=0%2C0&adpicid=0&lpn=0&ln=1241&fr=&fmq=1389861203899_R&fm=&ic=0&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=%E5%9B%BE%E7%89%87%E5%94%AF%E7%BE%8E&objurl=http%3A%2F%2Fimg.qikula.com%2Ffile%2Fimage%2Fpic%2F4a94782098n1643911844c26.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bqth7sw_z%26e3Bv54AzdH3Ft4w2jfAzdH3Fmn99na8amb_z%26e3Bip4s&gsm=e&rpstart=0&rpnum=0&islist=&querylist=&force=undefined");

                Log.d(TAG, "" + "!!!!" + photoPaths.size());
                if (paiZhaoAdapter == null) {
                    paiZhaoAdapter = new PaiZhaoAdapter(
                            photoPaths, KssmFragment.this.getActivity());
                    gridView.setAdapter(paiZhaoAdapter);
                }
                if (paiZhaoAdapter.getCount() > 0) {
                    paiZhaoAdapter.notifyDataSetChanged();
                }
            }
        });


    }

    /***
     * 网络请求时获取图片
     */
    private void DownIimage() {
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onViewCreated(view, savedInstanceState);
        uflag = true;// 初始化用户重复验证的标识
        tv_sign1.setEnabled(true);// 初始化签名不可点击// 放开签名布局
        tv_sign2.setEnabled(true);// 初始化签名不可点击true  // 放开签名布局
//        try {
//            //派工单
//            paigongdan = rw.getPaigongDan();// 派工单
//            Log.e(TAG, "派工单" + paigongdan);
//        } catch (Exception e) {
//            new AlertDialog.Builder(getActivity()).setMessage("派工单异常").show();
//        }

    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
//        if (mFingerUtil == null) {
//            mFingerUtil = new FingerUtil(getActivity(), this);
//        }

    }

    /**
     * 初始化控件
     */
    public void initView() {
        zzxlist_check = (LinearLayout) view.findViewById(R.id.zzxlist_check);
        qianmingLayout = (LinearLayout) view.findViewById(R.id.qianming_layout);// 签名布局
        banfengbao = (LinearLayout) view.findViewById(R.id.banfengbao);// 半封包
        quanfengbao = (LinearLayout) view.findViewById(R.id.quanfengbao);// 全封包
        gridView = (PaizhaoGridView) view.findViewById(R.id.gridView1);// 开始拍照列表
        startpaizhao = (TextView) view.findViewById(R.id.startpaizhao);// 开始拍照
        startpaizhao.setFocusable(true);
        startjiaojie = (TextView) view.findViewById(R.id.startjiaojie);// 开始交接
        qrwanceng = (TextView) view.findViewById(R.id.qrwanceng);// 确认完成
        zzxlist_layout_view = (LinearLayout) view
                .findViewById(R.id.zzxlist_layout_view);
        zzxlist_layout = (LinearLayout) view.findViewById(R.id.zzxlist_layout);// 填充器
        tv_sign1 = (TextView) view.findViewById(R.id.tv_sign1);// 签名提示1
        tv_sign2 = (TextView) view.findViewById(R.id.tv_sign2);// 签名提示2
        iv_sign1 = (ImageView) view.findViewById(R.id.iv_sign1);// 签名图片1
        iv_sign2 = (ImageView) view.findViewById(R.id.iv_sign2);// 签名图片2
        tv_sign3 = (TextView) view.findViewById(R.id.tv_sign3);// 用户名(半封包)
        tv_sign4 = (TextView) view.findViewById(R.id.tv_sign4);// 用户名(半封包)
        iv_sign3 = (ImageView) view.findViewById(R.id.iv_sign3);// 用户（指纹）图片(半封包)
        iv_sign4 = (ImageView) view.findViewById(R.id.iv_sign4);// 用户（指纹）图片(半封包)
        tv_sign5 = (TextView) view.findViewById(R.id.tv_sign5);// 用户名(全封包)
        iv_sign5 = (ImageView) view.findViewById(R.id.iv_sign5);// 用户（指纹）图片(全封包)
        back = (TextView) getActivity().findViewById(R.id.back);

        /*
         * 初始化与密码锁相关的变量
		 * @author zhouKai
		 */
        /** 设置监听事件 */
        back.setOnClickListener(this);
//        startsaomiao.setOnClickListener(this);
        startpaizhao.setOnClickListener(this);
        startjiaojie.setOnClickListener(this);
        gridView.setOnItemClickListener(this);
        gridView.setOnItemLongClickListener(this);
        qrwanceng.setOnClickListener(this);

        back.setText("返回");
        tv_sign1.setOnClickListener(this);
        iv_sign1.setOnClickListener(this);
    }

    public Handler getHandler() {

        return handler;
    }

    /**
     * 扫描通知
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0: // 显示扫描的结果
                    String zzxt = (String) msg.obj;
                    if ("箱子规格不正确".equals(zzxt)) {
                        return;
                    } else {
                        showSaomiao();///更改了方法
                    }
                    break;
                case 1:
                    break;
                case 2:
                    // 上传图片显示进度条
                    showJindu();
                    break;
                case 3:// 上传失败
                    OnClickUpload();// 重新上传
                    deleteDialog.setTitle("上传失败");
                    break;
                case 4:
                    progressDialog.dismiss();
                    // 调用提交任务接口
                    submit();
                    break;
                case 5:
                    // 提交成功后跳转
                    successDialog = dmanager.getSuccessDialog().builder();
                    subDialog.dismiss();
                    successDialog.show();
                    successDialog.success();
                    successDialog.setSuccess(new OnClickListener() {
                        public void onClick(View arg0) {
                            /** 跳转页面 */
                        /*
                         * FragmentTransaction ft = fm.beginTransaction();
						 * MyRenwuFragment fragment = new MyRenwuFragment();
						 * 
						 * fragment.setArguments(bundle);
						 * ft.replace(R.id.main_frame, fragment).commit();
						 */
                            bundle.putString("cid", cid);
                            mCallback.onArticleSelected(MyRenwuFragment.RENWU_TAG,
                                    bundle, KssmFragment.this);
                        }
                    });
                    break;
                case 6:
                    subDialog.dismiss();
                    OnClickSubmit();// 重新提交 提交失败
                    deleteDialog.setTitle("提交失败");
                    break;
                case 7:
                    subDialog.dismiss();
                    OnClickSubmit();// 重新提交 超时
                    deleteDialog.setTitle("提交超时");
                    break;
                case 10:// 登录框传过来的用户名和密码
                    Bundle bundle = msg.getData();
                    userId = bundle.getString("name");// 获取用户账号
                    pwd = bundle.getString("pwd");// 密码
                    if (userId.equals(fristUserId)) {// 如果相同，则提示用户已经验证
                        useDialog.show();// 重新登录
                        useDialog.setTitle("请换其他用户验证");
                    } else {
                        yanzhengUser(userId, pwd);
                    }
                    break;
                case 11:
                    // 登录验证
                    loginView();
                    break;
                case 12:// 用户不存在
                    dialog.dismiss();
                    Toast.makeText(getActivity(), app.fanhuiMsg, Toast.LENGTH_SHORT)
                            .show();
                    useDialog.show();// 重新登录
                    break;
                case 13:// 登录超时
                    dialog.dismiss();
                    Toast.makeText(getActivity(), app.fanhuiMsg, Toast.LENGTH_SHORT)
                            .show();
                    OnLoginClick();
                    deleteDialog.setTitle("登录超时");
                    break;
                case 14:// 登录异常 服务器断开连接了
                    dialog.dismiss();
                    Toast.makeText(getActivity(), app.fanhuiMsg, Toast.LENGTH_SHORT)
                            .show();
                    OnLoginClick();
                    break;

            }
        }

        ;
    };


    @Override
    public void onStart() {
        super.onStart();
        tv_sign1.setFocusable(true);
        if (list.size() > 0) {// 周转箱集合
            zzxlist_layout_view.setVisibility(View.VISIBLE);
            zzxlist_layout.setVisibility(View.GONE);// 显示填充器
        } else {
            zzxlist_layout_view.setVisibility(View.GONE);
            zzxlist_layout.setVisibility(View.VISIBLE);// 不显示填充器
        }
        String path = getActivity().getApplicationContext().getFilesDir()
                .getAbsolutePath();
        File  exdir=   Environment.getExternalStorageDirectory();
        embed = "/embed.txt";
        File file=new File(exdir,embed);
        embedPath = getActivity().getApplicationContext().getFilesDir()
                .getAbsolutePath()
                + "/";
        /* 新建签名文件TXT */
//        File file = new File(embed);
//        File file = new File(fulltule,embed);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        strPath = Environment.getExternalStorageDirectory().toString()
                + "/images/";// 存放照片的文件夹
        file = new File(strPath);
        if (!file.exists()) {
            file.mkdirs();

        }
    }

    @Override
    public void onDestroy() {
        saomiao.close();

        if (reader != null) {// 关闭扫描功能
            reader.close();
        }

        super.onDestroy();
    }

    /**
     * 调用系统拍照功能
     */
    @SuppressLint("SimpleDateFormat")
    protected void letCamera() {
        Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        signTitle = new SimpleDateFormat("yyyyMMddHHmmss")
                .format(new Date());// 照片命名
        file = new File(strPath, signTitle + ".jpg");
        Uri uri = Uri.fromFile(file);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(imageCaptureIntent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            namelist.add(file.getName());
            final String currentTime = "" + System.currentTimeMillis();
            Bitmap bitmap = BitmapUtil.getSmallBitmap(file.getAbsolutePath());
            final String path = BitmapUtil.createFile(strPath, bitmap, ""
                    + currentTime + ".jpg");
            final String newPic = embedPath + currentTime + ".jpg";
            if (bitmap != null) {
                bitmap.recycle();
                bitmap = null;
            }

            /**
             * 添加水印
             */
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        /*
                         * begin
						 * modify by wangmeng 2017-12-12
						 * 增加签名信息记录，方便上门服务系统中信息展示
						 */

                        /**
                         * 获取服务器时间
                         */
                        String time = UpServer.getcurrentTime();
                        /*BufferedWriter writer = new BufferedWriter(
                                new FileWriter(embed, false));
						File file = new File(filePath);
						FileOutputStream fileOutputStream = getActivity().openFileOutput(fileName,  
						Context.MODE_PRIVATE); */

                        String fileContext = rw.getCompany() + "_" + paigongdan + "_" + time;
                        signInfo.put(signTitle, fileContext);

						/*byte[] temBytes = fileContext.getBytes();  
                        fileOutputStream.write(temBytes);
						fileOutputStream.close(); 
						
						writer.write();
						writer.flush();
						writer.close();*/

						/*
                         * end
						 * modify by wangmeng 2017-12-12
						 * 增加签名信息记录，方便上门服务系统中信息展示
						 */
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    String str = operation.embed(path, embed, newPic);
                    if (TextUtils.isEmpty(str)) {
                        Log.i("---------", "embed is fail");
                    } else {
                        Log.i("---------", str);
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                pathlist.add(newPic);
                                photoPaths.add(newPic);
                                if (paiZhaoAdapter == null) {
                                    paiZhaoAdapter = new PaiZhaoAdapter(
                                            photoPaths, getActivity());
                                    gridView.setAdapter(paiZhaoAdapter);
                                }
                                if (paiZhaoAdapter.getCount() > 0) {
                                    paiZhaoAdapter.notifyDataSetChanged();
                                    startjiaojie
                                            .setBackgroundResource(R.drawable.saomiao_selector);
                                    startjiaojie.setEnabled(true);
                                }
                            }
                        });
                    }
                }
            }).start();
        }
    }


    /**
     * 单击事件
     */
    long lastClick = 0;


    public void onClick(View arg0) {

        switch (arg0.getId()) {

            case R.id.startpaizhao:// 开始拍照
                if (System.currentTimeMillis() - lastClick <= 2000) {
                    return;
                }
                lastClick = System.currentTimeMillis();
                zzxlist_check.setVisibility(View.GONE);
                letCamera();
                startsaomiao.setEnabled(false);
                startsaomiao.setBackgroundResource(R.drawable.button_gray);
                break;
            case R.id.startjiaojie:// 开始交接 目前是用户名和密码通过
                startpaizhao.setBackgroundResource(R.drawable.button_gray);
                startpaizhao.setEnabled(false);
                String title = fengbaostate == 0 ? "上门人员验证" : "押运员验证";
                if (threeTimes == true) {
                    useDialog.show();
                    useDialog.setTitle(title);
//                    mFingerUtil.stopControl();
                } else {
//                    Toast.makeText(getActivity(), "请" + title + "指纹..",
//                            Toast.LENGTH_LONG).show();
//                    if (mFingerUtil.getThread() == null) {
//                        mFingerUtil.startFinger();
//                    } else {
//                        mFingerUtil.startControl();
//                    }
                }
                break;
            case R.id.qrwanceng:// 确认完成 切换fragment
            /*
             * 在上传图片之前要求密码锁全部是闭锁状态
			 * @author zhouKai
			 */
//                if ((this.decodeLock.isUsed && this.decodeLock.isAllLocked())) {
                    UploadnImage();// 图片上传
//                }
                break;
            case R.id.tv_sign1:// 签名一
                qianmingLeft();
                break;
            case R.id.tv_sign2:// 签名二
//                qianmingRight();
                break;
            case R.id.back:// 返回键处理
            /*
             * FragmentTransaction ft = fm.beginTransaction(); StartFwFragment
			 * fragment = new StartFwFragment(); bundle.putSerializable("rw",
			 * (Serializable) rw); bundle.putString("cid", cid);
			 * fragment.setArguments(bundle); ft.addToBackStack(null);
			 * ft.replace(R.id.main_frame, fragment).commit();
			 */
                //当返回按钮时停止扫描

                if (getActivity() != null) {
                    getActivity().onBackPressed();
                }
                break;
        }
    }

    /**
     * 错误箱子处理
     */
    public void doError(String strbox) {
        String wuxiaoBox = "";
        String chongfuBox = "";
        String[] tr = strbox.split(",");
        for (int i = 0; i < tr.length; i++) {
            String str = tr[i].substring(tr[i].length() - 1, tr[i].length());
            if ("|".equals(str)) {// 无效的箱子
                wuxiaoBox = wuxiaoBox + tr[i].replace("|", "") + ",";
            } else {// 重复的箱子
                Log.e(TAG, "chongfuBox===" + chongfuBox + tr[i].trim() + ",");
                chongfuBox = chongfuBox + tr[i].trim() + ",";

            }
        }
        int wuSize = wuxiaoBox.length();
        int chongSize = chongfuBox.length();
        StringBuffer sb = new StringBuffer();
        TextView tv = successDialog.addTextView();
        tv.setTextSize(20);
        tv.setTypeface(Typeface.DEFAULT_BOLD);
        tv.setTextColor(getResources().getColor(R.color.red));
        if (wuSize != 0) {
            sb.append(getResources().getString(R.string.error_box));
            tv.setText(wuxiaoBox.substring(0, wuSize - 1));
        }

        if (chongSize != 0) {
            sb.append(getResources().getString(R.string.repeat_box));
            tv.setText(chongfuBox.substring(0, chongSize - 1));
        }

        successDialog.show();
        successDialog.failure();
        successDialog.setTitle(sb.toString());
        successDialog.setTextSize(25);
        successDialog.getrootView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                successDialog.dismiss();
            }
        });
    }

    /**
     * @throws
     * @author 名字
     * @Description: 周转箱ID拼接
     */
    private String dividerBoxes(List<String> boxes) {
        String result = "";
        int size = boxes.size();
        for (int i = 0; i < size; i++) {
            Log.e(TAG, "验证周转箱kss===========" + boxes);
            result += boxes.get(i) + "_";
            Log.e(TAG, boxes.get(i) + "_" + "======" + result);
        }
        return result;
    }

    /**
     * 签名一
     */
    WritePadDialog writeTabletDialog;

    public void qianmingLeft() {
        if (writeTabletDialog != null) {
            if (!writeTabletDialog.isShowing()) {
                writeTabletDialog.show();
            }
        } else {
            writeTabletDialog = new WritePadDialog(getActivity(),
                    new DialogListener() {
                        public void refreshActivity(Object object) {
                            Bitmap map = (Bitmap) object;// 得到回传的图片
                            final String currentTime = ""
                                    + System.currentTimeMillis();
                            leftName = currentTime + ".jpg";
                            final String path = BitmapUtil.createFile(strPath,
                                    map, leftName);
                            Log.i("---LOG_TAG---", "原1" + path);
//                            final String newPic = embedPath + currentTime
//                                    + ".jpg";
                            final String newPic2 = currentTime
                                    + ".jpg";
//                            File file = new File(Environment.getExternalStorageDirectory(),newPic2);
                            final String newPic = getExternalStorageDirectory().toString() +"/images/"+ currentTime + ".jpg";

                            addWatermark(leftName, newPic, path, map, tv_sign1,
                                    iv_sign1, currentTime);

                        }
                    }, strPath + namelist.get(0));
        }
        writeTabletDialog.show();

    }

    /**
     * 签名二
     */
//    WritePadDialog wd;
//
//    public void qianmingRight() {
//        if (wd != null) {
//            if (!wd.isShowing()) {
//                wd.show();
//            }
//        } else {
//            wd = new WritePadDialog(getActivity(), new DialogListener() {
//                public void refreshActivity(Object object) {
//                    Bitmap map = (Bitmap) object;
//                    String currentTime = "" + System.currentTimeMillis();
//                    rightName = currentTime + ".jpg";
//                    final String path = BitmapUtil.createFile(strPath, map,
//                            rightName);
//                    Log.i("---LOG_TAG---", "原1" + path);
//                    final String newPic = embedPath + currentTime + ".jpg";
//                    addWatermark(rightName, newPic, path, map, tv_sign2,
//                            iv_sign2, currentTime);
//                }
//            }, getPhoto());
//
//            wd.show();
//        }
//    }

    /**
     * 签名图片添加水印 图片bitmap map 签名人控件TextView signName 签名人图片控件 signImg 图片名字
     */
    public void addWatermark(final String picName, final String newPic,
                             final String path, Bitmap map, final TextView signName,
                             final ImageView signImg, final String currentTime) {

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    /*
                     * begin
					 * modify by wangmeng 2017-12-12
					 * 增加签名信息记录，方便上门服务系统中信息展示
					 */

                    /**
                     * 获取当前服务器时间
                     */
//                    String time = UpServer.getcurrentTime();
                    String time = "0001";
                    /*BufferedWriter writer = new BufferedWriter(
                            new FileWriter(embed, false));
					File file = new File(filePath);
					FileOutputStream fileOutputStream = getActivity().openFileOutput(fileName,  
					Context.MODE_PRIVATE); */

//                    String fileContext = paigongdan + "_" + time + "_" + signName.getText().toString();
                    String fileContext = time + "_" + signName.getText().toString();
                    signInfo.put(currentTime, fileContext);

					/*byte[] temBytes = fileContext.getBytes();  
                    fileOutputStream.write(temBytes);
					fileOutputStream.close(); 
					
					String time = UpServer.getcurrentTime();
					BufferedWriter writer = new BufferedWriter(new FileWriter(
							embed, false));
					writer.write(paigongdan + "_" + time + "_"
							+ signName.getText().toString());
					writer.flush();
					writer.close();*/

					/*
                     *end
					 * modify by wangmeng 2017-12-12
					 * 增加签名信息记录，方便上门服务系统中信息展示
					 */
                } catch (Exception e) {

                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 调用jni  ndk 东西
                String str = operation.embed(path, embed, newPic);
                if (TextUtils.isEmpty(str)) {
                    Log.i("---------", "embed is fail");
                } else {
                    Log.i("---------", str);
                }
                getActivity().runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        pathlist.add(newPic);// 将签名图片路径放入图片路径集合中
                        namelist.add(picName);// 将签名图片名放入图片名集合中
                        Log.e(TAG,"newPic--------------------"+newPic);
                        Glide.with(getActivity()).load(newPic).into(signImg);
                        signName.setVisibility(View.GONE);// 隐藏签名提示
                        if (leftName != null) {// 开启下个功能操作   提交
                            qrwanceng.setEnabled(true);
                            qrwanceng
                                    .setBackgroundResource(R.drawable.saomiao_selector);
                        }

                    }
                });
            }
        }).start();

    }

    /**
     * dialog no dismiss
     */
    OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };

    /**
     * 获取第2张照片
     */
    private String getPhoto() {
        String s = "";
        if (paiZhaoAdapter.getCount() == 1) {
            return s = strPath + namelist.get(0);
        } else {
            s = strPath + namelist.get(1);
        }

        return s;
    }

    /**
     * 图片上传接口
     */
    public void UploadnImage() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    String result = UpServer.upCkRenWuState(paigongdan,
                            App.getApp().userZhanghao);
                    if ("success".equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                flag = 1;
                                imageNum = 0;
                                progressDialog.show();
                                progressDialog.setTitle("正在上传第1张图片");
                                progressDialog.setProgress(0);
                                // 给进度条
                                new Thread(new Runnable() {
                                    public void run() {
                                        try {
                                            MD5 md = new MD5();// MD5传图片
                                            // 确保图片的唯一性和完整性
                                            for (int i = 0; i < pathlist.size(); i++) {
                                                 /*
                                                 * begin
												 * modify by wangmeng 2017-12-12
												 * 往接口中添加签名信息
												 */

                                                String name = namelist.get(i).substring(0, namelist.get(i).indexOf("."));
                                                String length = md
                                                        .getMd5(pathlist.get(i));// 根据图片全路径生成MD5码
                                                String sss = UpServer.uploadImg(
                                                        BitmapUtil
                                                                .getBytes(pathlist
                                                                        .get(i)),
                                                        namelist.get(i), length,
                                                        signInfo.get(name));
                                                /*
                                                 * end
												 * modify by wangmeng 2017-12-12
												 * 往接口中添加签名信息
												 */
                                                handler.sendEmptyMessage(2);

                                            }
                                        } catch (Exception e) {
                                            handler.sendEmptyMessage(3);
                                        }
                                    }
                                }).start();
                            }
                        });
                    } else if ("error".equals(result)) {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                DeleteDialog dialog = new DeleteDialog(
                                        getActivity()).builder();
                                dialog.setTitle("当前任务已被撤销..");
                                dialog.setOnlyButton();
                                dialog.setPositiveButton("确定",
                                        new OnClickListener() {

                                            @Override
                                            public void onClick(View arg0) {
                                                FragmentTransaction ft = fm
                                                        .beginTransaction();
                                                MyRenwuFragment fragment = new MyRenwuFragment();
//                                                bundle.putString("cid", cid);
                                                fragment.setArguments(bundle);
                                                ft.replace(R.id.main_frame,
                                                        fragment).commit();
                                            }
                                        });
                                dialog.show();
                                qrwanceng
                                        .setBackgroundResource(R.drawable.button_gray);
                                qrwanceng.setEnabled(false);
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 图片上传完--提交任务
     */
    public void submit() {
        flag = 2;
        subDialog.show();
        getSubmitCanshu();// 获取接口所需的参数
        new Thread(new Runnable() {
            public void run() {
                String signName = "";
                if (!TextUtils.isEmpty(rightName)) {
                    signName = leftName + "_" + rightName;
                } else {
                    signName = leftName;
                }
                try {
                    String result = UpServer.setRenwuLingqus(fengbaostate,
                            userid, qiyeyuan, paigongdan, zhouzhuangxiang,
                            fileNamelist, signName);
                    if ("success".equals(result)) {
                        handler.sendEmptyMessage(5);
                    } else {// 失败
                        handler.sendEmptyMessage(6);
                    }
                } catch (SocketException e) {// 超时
                    e.printStackTrace();
                    handler.sendEmptyMessage(7);
                } catch (Exception e) {// 失败
                    e.printStackTrace();
                    handler.sendEmptyMessage(6);
                }
            }
        }).start();

    }

    /**
     * 用户验证
     */
    public void yanzhengUser(final String name, final String pwd) {
        dialog.show();
        dialog.setMessage("正在验证用户...");
        new Thread(new Runnable() {
            public void run() {
                try {
                    user = UpServer.login(name, pwd);
                    Log.e(TAG, "!!!!!!!!!!!!!!!!!!!!!!!!!!" + user);
                    if (user != null) {
                        handler.sendEmptyMessage(11);
                    } else {
                        handler.sendEmptyMessage(12);// 查无此人信息
                    }
                } catch (SocketTimeoutException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(13);// 超时链接
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(12);// 查无此人信息
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(14);// 登录异常
                }
            }
        }).start();
    }

    /**
     * 上传图片后--得到提交的参数
     */
    public void getSubmitCanshu() {


//        arrayListzhou.add(decodeLock.setSendLockNumber());//添加到箱子
        Log.e(TAG, "arrayList" + arrayListzhou.size());
        qiyeyuan = "";
        for (int i = 0; i < plist.size(); i++) {
            qiyeyuan += plist.get(i).getPid() + "_";
        }
        qiyeyuan = qiyeyuan.substring(0, qiyeyuan.length() - 1).trim();// 企业人员
        zhouzhuangxiang = "";
        for (int i = 0; i < arrayListzhou.size(); i++) {
            zhouzhuangxiang += arrayListzhou.get(i) + "_";
        }
        zhouzhuangxiang = zhouzhuangxiang.substring(0,
                zhouzhuangxiang.length() - 1).trim();// 周转箱
        fileNamelist = "";
        if (plist.size() == 1) {
            for (int i = 0; i < namelist.size() - 1; i++) {// 因为最后1张图片为签名的图片的名称，要分开
                fileNamelist += namelist.get(i) + "_";
            }
        } else {
            for (int i = 0; i < namelist.size() - 2; i++) {// 因为最后2张图片为签名的图片的名称，要分开
                fileNamelist += namelist.get(i) + "_";
            }
        }
        fileNamelist = fileNamelist.substring(0, fileNamelist.length() - 1)
                .trim();// 图片名称
    }

    /**
     * 上传图片失败重试
     */
    public void OnClickUpload() {
        deleteDialog.show();
        deleteDialog.setPositiveButton("重试", new OnClickListener() {
            public void onClick(View arg0) {
                UploadnImage();
            }
        }).setNegativeButton("取消", new OnClickListener() {
            public void onClick(View arg0) {
                if (flag == 1) {
                    progressDialog.dismiss();
                } else {
                    subDialog.dismiss();
                }
            }
        });
    }

    /**
     * 提交失败重试
     */
    public void OnClickSubmit() {
        deleteDialog.show();
        deleteDialog.setPositiveButton("重试", new OnClickListener() {
            public void onClick(View arg0) {
                submit();
            }
        }).setNegativeButton("取消", new OnClickListener() {
            public void onClick(View arg0) {
                if (flag == 1) {
                    progressDialog.dismiss();
                } else {
                    subDialog.dismiss();
                }
            }
        });
    }

    /**
     * 用户登录失败重试
     */
    public void OnLoginClick() {
        deleteDialog.show();
        deleteDialog.setTitle("登录异常");
        deleteDialog.setPositiveButton("重试", new OnClickListener() {
            public void onClick(View arg0) {
                yanzhengUser(userId, pwd);
            }
        });
        deleteDialog.setNegativeButton("取消", new OnClickListener() {
            public void onClick(View arg0) {
            }
        });
    }

    /**
     * 照片点击放大
     */
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Log.e(TAG,photoPaths.size()+"photoPathsc   -----长度");
        bundle.putString("map", photoPaths.get(arg2));
        Skip.skip(getActivity(), BigMapActivity.class, bundle, 0);
    }

    /**
     * 长按删除
     */
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                   final int position, long arg3) {
        // 弹出Dialog 提示是否要进行删除
        deleteDialog.show();
        deleteDialog.setTitle("是否要删除");
        deleteDialog.setPositiveButton("确定", new OnClickListener() {
            public void onClick(View arg0) {
                pathlist.remove(position);// 删除照片的路径
                photoPaths.remove(position); // 删除显示的照片
                paiZhaoAdapter.notifyDataSetChanged();
                if (photoPaths.size() == 0) {
                    startjiaojie.setBackgroundResource(R.drawable.button_gray);
                    startjiaojie.setEnabled(false);
                }

            }
        }).setNegativeButton("取消", new OnClickListener() {
            public void onClick(View arg0) {
            }
        });
        return true;// 防止其在触发列表点击事件
    }

    /**
     * 进度条显示
     */
    public void showJindu() {
        imageNum++;
        int jindu = imageNum * 100 / pathlist.size();// 计算进度条显示的数值
        progressDialog.setProgress(jindu);// 设置进度条百分比
        if (imageNum == pathlist.size()) {// 上传完毕
            progressDialog.setTitle("上传完毕...");
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(1000);
                        handler.sendEmptyMessage(4);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        } else {
            progressDialog.setTitle("正在上传第" + (imageNum + 1) + "张图片...");
        }
    }

    /**
     * 扫描显示
     */
    public void showSaomiao() {
        if (list.size() > 0) {
            zzxlist_layout_view.setVisibility(View.VISIBLE);//周转箱列表显示
            zzxlist_layout.setVisibility(View.GONE);
        } else {
            zzxlist_layout_view.setVisibility(View.GONE);
            zzxlist_layout.setVisibility(View.VISIBLE);
        }
        /*
         * 更新界面，显示扫描到的周转箱
		 * @author zhouKai
		 */

        this.decodeLock.notifyZzxNumListChange();
        // zhouzxAdapter.notifyDataSetChanged()// 刷新视图

    }

    /**
     * 登录
     */
    public void loginView() {
        if (dialog != null) {
            dialog.dismiss();
        }
        if (fengbaostate == 0) {// 半封包模式
            int size = userList.size();
            for (int i = 0; i < size; i++) {
                Log.i("dg", userList.get(i).getName());
                if (userList.get(i).getName().equals(user.getName())) {

                    break;
                }
                if (i == size - 1) {//要求用户不一致不能按压当用户一致时能够按压
                    showToastUtils.showBigToast("用户不一致..", Toast.LENGTH_LONG);
                    return;
                }
            }

            if ("".equals(tv_sign3.getText().toString())
                    || tv_sign3.getText().toString() == null) {
                if (user.getUserId().equals(Constant.SmRoleId)) {// 上门人员登录
                    userid = userId + "_";
                    tv_sign3.setText(user.getName());// 验证成功后在相应的地方显示用户名
                    if (uflag) {
                        fristUserId = userId;
                        uflag = false;
                    }
                    iv_sign3.setImageBitmap(null);
                    iv_sign3.setBackgroundResource(R.drawable.sccuss);
                    // useDialog.show();
                    Toast.makeText(getActivity(), "请人员进行指纹验证..",
                            Toast.LENGTH_LONG).show();
//                    mFingerUtil.startControl();
                    useDialog.setTitle("上门人员二登录");
                } else {
                    Toast.makeText(getActivity(), "请使用上门人员验证..",
                            Toast.LENGTH_LONG).show();
                    useDialog.setTitle("上门人员一登录");
                }
            } else {
                if (user.getUserId().equals(Constant.SmRoleId)
                        && !tv_sign3.getText().toString()
                        .equals(user.getName())) {// 上门人员登录

                    userid = userid + userId;
                    tv_sign4.setText(user.getName());// 验证成功后在相应的地方显示用户名
                    iv_sign4.setImageBitmap(null);
                    iv_sign4.setBackgroundResource(R.drawable.sccuss);
                    if (plist.size() == 1) {
                        tv_sign1.setEnabled(true);
                        tv_sign1.setText(plist.get(0).getName());
                        qianmingLayout.setVisibility(View.GONE);
                    } else if (plist.size() == 2) {
                        tv_sign1.setEnabled(true);
                        tv_sign2.setEnabled(true);// 用户名验证成功后可以进行签名
                        tv_sign1.setBackgroundColor(Color.parseColor("#4ec1fc"));
                        tv_sign2.setBackgroundColor(Color.parseColor("#4ec1fc"));
                        tv_sign1.setText(plist.get(0).getName());
                        tv_sign2.setText(plist.get(1).getName());
                    }
                    startjiaojie.setEnabled(false);
                    startjiaojie.setBackgroundResource(R.drawable.button_gray);
                } else if (user.getUserId().equals(Constant.SmRoleId)
                        && tv_sign3.getText().toString().equals(user.getName())) {
                    Toast.makeText(getActivity(), "用户重复验证,请重试...",
                            Toast.LENGTH_LONG).show();
                    if (threeTimes == true) {
                        useDialog.show();
                        useDialog.setTitle("上门人员二登录");
//                        mFingerUtil.stopControl();
                    } else {
//                        if (mFingerUtil.getThread() == null) {
//                            mFingerUtil.startFinger();
//                        } else {
//                            mFingerUtil.startControl();
//                        }
                    }

                } else {
                    Toast.makeText(getActivity(), "请使用上门人员验证..",
                            Toast.LENGTH_LONG).show();
                    if (threeTimes == true) {
                        useDialog.show();
                        useDialog.setTitle("上门人员二登录");
//                        mFingerUtil.stopControl();
                    } else {
//                        if (mFingerUtil.getThread() == null) {
//                            mFingerUtil.startFinger();
//                        } else {
//                            mFingerUtil.startControl();
//                        }
                    }
                }
            }
        } else {// 全封包模式
            if (!app.user.getName().equals(user.getName())) {
                showToastUtils.showBigToast("用户不一致！", Toast.LENGTH_LONG);
                return;
            }
            if ("".equals(tv_sign5.getText().toString()) || tv_sign5.getText().toString() == null) {
                if (user.getUserId().equals(Constant.YyRoleId)) {// 押运人员登录
                    userid = userId + "_";
                    tv_sign5.setText(user.getName());// 验证成功后在相应的地方显示用户名

                    iv_sign5.setImageBitmap(null);
                    iv_sign5.setBackgroundResource(R.drawable.sccuss);
                    if (plist.size() == 1) {
                        tv_sign1.setEnabled(true);
                        tv_sign1.setText(plist.get(0).getName());
                        qianmingLayout.setVisibility(View.GONE);
                    } else if (plist.size() == 2) {
                        tv_sign1.setEnabled(true);
                        tv_sign2.setEnabled(true);// 用户名验证成功后可以进行签名
                        tv_sign1.setText(plist.get(0).getName());
                        tv_sign2.setText(plist.get(1).getName());
                        tv_sign1.setBackgroundColor(Color.parseColor("#4ec1fc"));
                        tv_sign2.setBackgroundColor(Color.parseColor("#4ec1fc"));
                    }
                    startjiaojie.setEnabled(false);
                    startjiaojie.setBackgroundResource(R.drawable.button_gray);
                } else {
                    useDialog.setTitle("请用押运员登录");
                    showToastUtils.showBigToast("请使用押运员验证..", Toast.LENGTH_SHORT);
                }
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
//        if (mFingerUtil != null) {
//            mFingerUtil.stopFinger();
//        }
    }

    /**
     * 覆盖水印文件或继续写
     */
    private void writePoka() {
        /*
         * try { BufferedWriter writer = new BufferedWriter( new
		 * FileWriter(embed, false)); writer.write(paigongdan + "_" +
		 * currentTime + "_" + tv_sign1.getText().toString()); writer.flush();
		 * writer.close(); } catch (IOException e) { // TODO Auto-generated
		 * catch block e.printStackTrace(); }
		 */
    }

    /**
     * 得到指纹值
     */
    @Override
    public void getFingerValue(byte[] value) {
//        mFingerUtil.stopControl();
        String corpId;
        String roleId;
        if (fengbaostate == 0) {
            corpId = jigouId;
            roleId = Constant.SmRoleId;
        } else {
            corpId = App.getApp().user.getOrganizationId();
            roleId = Constant.YyRoleId;
        }
//        mFingerUtil.startTconfrim(corpId, roleId, value);
    }

    /**
     * 得到指纹图片
     */
    @Override
    public void getFingerBitmap(Bitmap bitmap) {
        if (fengbaostate == 0) {
            if (TextUtils.isEmpty(tv_sign3.getText().toString())) {
                iv_sign3.setImageBitmap(bitmap);
            } else {
                iv_sign4.setImageBitmap(bitmap);
            }
        } else {
            iv_sign5.setImageBitmap(bitmap);
        }

    }

    /**
     * 指纹验证成功
     */
    @Override
    public void getFingerSuccess(User user) {
        this.user = user;
        times = 0;
        userId = user.getAccount();
        if (fengbaostate == 0) {
            this.user.setUserId(Constant.SmRoleId);
        } else {
            this.user.setUserId(Constant.YyRoleId);
        }
        loginView();
    }

    /**
     * 指纹验证失败
     */
    @Override
    public void getFingerFail() {
        times++;
        if (times == 3) {
            threeTimes = true;// 失败3次
        } else {
            threeTimes = false;// 未失败3次
        }
        new DeleteDialog(getActivity())
                .builder()
                .setTitle(
                        times == 3 ? "指纹验证失败3次,请使用密码登陆" : "指纹验证失败" + times
                                + "次")
                .setOnlyButton()
                .setkeyListener(keylistener)
                .setPositiveButton(times == 3 ? "密码登陆" : "重新验证",
                        new OnClickListener() {

                            @Override
                            public void onClick(View arg0) {
                                iv_sign3.setImageBitmap(null);
                                iv_sign4.setImageBitmap(null);
                                // fingerHandler.sendMessageDelayed(fingerHandler.obtainMessage(21),
                                // 50);

								/* 判断错误次数，3次打开密码登陆界面 */
                                if (times == 3) {
                                    times = 0;
                                    useDialog.clear();
                                    useDialog.show();
                                    return;
                                }
                                /* 开启指纹数据发送开关 */
//                                mFingerUtil.startControl();
                            }
                        }).show();
    }


    public Handler getHandlerzhuannum() {

        return handlerzhuannum;
    }

    /**
     * 新版的开锁功能 查找到新的锁号码添加到集合中
     */
    public void searchLock() {
        byte[] reply = null;
        int locknum = 0;
        int count = 0;
        int lockitem = 0;
        List<String> rfidSerialID = new ArrayList();
        selectItem = "";
        String epcStr = "";
        receivelist.removeAllElement();
        rfidDevice.unSelectMode();
        createListener();//接收有效字节并实心抽象实现方法需要先覆盖发出发接收方法
        rfidDevice.searchEPC();//发送消息命令
        int replynum = receivelist.getElementNum();
        for (int i = 0; i < replynum; i++) {
            Log.e(TAG, "系统" + System.currentTimeMillis());
            reply = receivelist.getFinishElement();//轮询
            String replyString = com.poka_global_constant.Util.byte2HexStr(reply);
            if (!replyString.equals("BB01FF000115167E") && replyString.length() > 40) {
                LockID.add(replyString.substring(16, 40));
                rfidDevice.unSelectMode();
                rfidDevice.selectMode();
                reply = receivelist.getFinishElement();
                //限制普通标签被查到并添加到集合
                String strBox = null;
                list.clear();
                if (list.contains(replyString.substring(16, 40))) {
                    Log.e(TAG, "包含了此箱不添加");
                } else {

                    list.add(replyString.substring(16, 40));//将锁箱号码放到集合传入到开锁界面
                    epcStr = replyString.substring(16, 40);
                    strBox = epcStr;
                    listzou.add(Guolv(epcStr));
                    if (chongsao == 01) {
                        handlerzhuan = decodeLock.getHandler();
                        Message msg = new Message();
                        msg.obj = strBox;
                        msg.what = 999;
                        if (null != strBox && !"".equals(strBox)) {

                            handlerzhuan.sendMessage(msg);
                        }
                    }
                }
            }

            if (list.size() > 0) {// 周转箱集合
                rfidDevice.closeRFID();
                zzxlist_layout_view.setVisibility(View.VISIBLE);
                zzxlist_layout.setVisibility(View.GONE);// 显示填充器

            } else {
                zzxlist_layout_view.setVisibility(View.GONE);
                zzxlist_layout.setVisibility(View.VISIBLE);// 不显示填充器
            }
            if (count == GlobalConstant.TRY_TICK) {
                continue;
            }
        }
        if (list.size() <= 0) {
            showToastUtils.showBigToast("请检查电源并对准电池位置", 400);
            //如果 searchlock  无响应 重新  搜索
            if (lockitem > 3) {
                toomuchsearchlock();
                Log.e(TAG, "多次点击后执行此方法");
                lockitem = 0;
            }
        }

    }

    {
        listener = new RFIDDevice.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
                // TODO Auto-generated method stub
                // 如果接收序列为空直接将数据加入到接收序列中,
                byte[] tempbuffer = null;
                if (receivelist.getElementNum() != 0 && !receivelist.getLastElementStatus()) {
                    byte[] lastbuf = receivelist.getLastElement();
                    tempbuffer = new byte[lastbuf.length + size];
                    System.arraycopy(lastbuf, 0, tempbuffer, 0, lastbuf.length);
                    System.arraycopy(buffer, 0, tempbuffer, lastbuf.length, size);
                    receivelist.removeLastElement();
                } else {
                    tempbuffer = new byte[size];
                    System.arraycopy(buffer, 0, tempbuffer, 0, size);
                }
                // 按照接收buffer的最后一字节判断是否接收完毕   截取报文的头 BB头7E尾的
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length < 5) || (tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && (tempbuffer[4] + 7) > tempbuffer.length))
                    receivelist.addElement(tempbuffer, false);
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && ((int) tempbuffer[4] + 7) <= tempbuffer.length)) {
                    int bytelen = tempbuffer[4] + 7;
                    byte[] newbyte = new byte[bytelen];
                    System.arraycopy(tempbuffer, 0, newbyte, 0, bytelen);
                    receivelist.addElement(newbyte, true);
                    if ((tempbuffer.length - bytelen) > 0) {
                        newbyte = new byte[tempbuffer.length - bytelen];
                        System.arraycopy(tempbuffer, bytelen, newbyte, 0, tempbuffer.length - bytelen);
                        receivelist.addElement(newbyte, false);
                    }
                }
            }
        };
    }

    /**
     * 创建一个监听
     */
    private void createListener() {
        listener = new RFIDDevice.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
                // TODO Auto-generated method stub
                // 如果接收序列为空直接将数据加入到接收序列中,
                byte[] tempbuffer = null;
                if (receivelist.getElementNum() != 0 && !receivelist.getLastElementStatus()) {
                    byte[] lastbuf = receivelist.getLastElement();
                    tempbuffer = new byte[lastbuf.length + size];
                    System.arraycopy(lastbuf, 0, tempbuffer, 0, lastbuf.length);
                    System.arraycopy(buffer, 0, tempbuffer, lastbuf.length, size);
                    receivelist.removeLastElement();
                } else {
                    tempbuffer = new byte[size];
                    System.arraycopy(buffer, 0, tempbuffer, 0, size);
                }
                // 按照接收buffer的最后一字节判断是否接收完毕
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length < 5) || (tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && (tempbuffer[4] + 7) > tempbuffer.length))
                    receivelist.addElement(tempbuffer, false);
                if ((tempbuffer[0] == (byte) 0xBB && tempbuffer.length >= 5 && ((int) tempbuffer[4] + 7) <= tempbuffer.length)) {
                    int bytelen = tempbuffer[4] + 7;
                    byte[] newbyte = new byte[bytelen];
                    System.arraycopy(tempbuffer, 0, newbyte, 0, bytelen);
                    receivelist.addElement(newbyte, true);
                    if ((tempbuffer.length - bytelen) > 0) {
                        newbyte = new byte[tempbuffer.length - bytelen];
                        System.arraycopy(tempbuffer, bytelen, newbyte, 0, tempbuffer.length - bytelen);
                        receivelist.addElement(newbyte, false);
                    }
                }
            }
        };
        rfidDevice.setOnDataReceiveListener(listener);
    }


    /**
     * 过滤器
     *
     * @param str
     * @return
     */
    public String Guolv(String str) {
        String box = CaseString.getBoxNum(str);//这个方法以后自己去修改
        if (box.length() < 2) {
            return "";
        }
        String stx = box.substring(box.length() - 2, box.length());
        if ("ZZ".equals(stx)) {
            return box;
        } else {
            return "箱子规格不正确";
        }
        //	return box;
    }

    private void initContext() {
        createListener();
        rfidDevice.setOnDataReceiveListener(listener);
    }

    /***
     * 防止用户多次点击造成anr异常
     */


    public void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("提示");
        builder.setTitle("正在处理。。。。。");
        builder.setPositiveButton(" ", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();

            }
        });
    }

    /***
     * 多次查询无果
     */
    public void toomuchsearchlock() {

        rfidDevice.unSelectMode();
        searchLock();

    }

    public void itemNum() {
        if (fengbaostate == 0) {// 半封包模式
            int size = userList.size();
            for (int i = 0; i < size; i++) {
                Log.i("dg", userList.get(i).getName());
                if (userList.get(i).getName().equals(user.getName())) {

                    break;
                }
                if (i == size - 1) {//要求用户不一致不能按压当用户一致时能够按压

                    showToastUtils.showBigToast("用户不一致请重新交接..", Toast.LENGTH_LONG);
//                    mFingerUtil.startControl();
                    return;
                }
            }

            if ("".equals(tv_sign3.getText().toString())
                    || tv_sign3.getText().toString() == null) {
                if (user.getUserId().equals(Constant.SmRoleId)) {// 上门人员登录
                    userid = userId + "_";
                    tv_sign3.setText(user.getName());// 验证成功后在相应的地方显示用户名
                    if (uflag) {
                        fristUserId = userId;
                        uflag = false;
                    }
                    iv_sign3.setImageBitmap(null);
                    iv_sign3.setBackgroundResource(R.drawable.sccuss);
                    // useDialog.show();
                    Toast.makeText(getActivity(), "请人员进行指纹验证..",
                            Toast.LENGTH_LONG).show();
//                    mFingerUtil.startControl();
                    useDialog.setTitle("上门人员二登录");
                } else {
                    Toast.makeText(getActivity(), "请使用上门人员验证..",
                            Toast.LENGTH_LONG).show();
                    useDialog.setTitle("上门人员一登录");
                }
            } else {
                if (user.getUserId().equals(Constant.SmRoleId)
                        && !tv_sign3.getText().toString()
                        .equals(user.getName())) {// 上门人员登录

                    userid = userid + userId;
                    tv_sign4.setText(user.getName());// 验证成功后在相应的地方显示用户名
                    iv_sign4.setImageBitmap(null);
                    iv_sign4.setBackgroundResource(R.drawable.sccuss);
                    if (plist.size() == 1) {
                        tv_sign1.setEnabled(true);
                        tv_sign1.setText(plist.get(0).getName());
                        qianmingLayout.setVisibility(View.GONE);
                    } else if (plist.size() == 2) {
                        tv_sign1.setEnabled(true);
                        tv_sign2.setEnabled(true);// 用户名验证成功后可以进行签名
                        tv_sign1.setBackgroundColor(Color.parseColor("#4ec1fc"));
                        tv_sign2.setBackgroundColor(Color.parseColor("#4ec1fc"));
                        tv_sign1.setText(plist.get(0).getName());
                        tv_sign2.setText(plist.get(1).getName());
                    }
                    startjiaojie.setEnabled(false);
                    startjiaojie.setBackgroundResource(R.drawable.button_gray);
                } else if (user.getUserId().equals(Constant.SmRoleId)
                        && tv_sign3.getText().toString().equals(user.getName())) {
                    Toast.makeText(getActivity(), "用户重复验证,请重试...",
                            Toast.LENGTH_LONG).show();
                    if (threeTimes == true) {
                        useDialog.show();
                        useDialog.setTitle("上门人员二登录");
//                        mFingerUtil.stopControl();
                    } else {
//                        if (mFingerUtil.getThread() == null) {
//                            mFingerUtil.startFinger();
//                        } else {
//                            mFingerUtil.startControl();
//                        }
                    }

                } else {
                    Toast.makeText(getActivity(), "请使用上门人员验证..",
                            Toast.LENGTH_LONG).show();
                    if (threeTimes == true) {
                        useDialog.show();
                        useDialog.setTitle("上门人员二登录");
//                        mFingerUtil.stopControl();
                    } else {
//                        if (mFingerUtil.getThread() == null) {
//                            mFingerUtil.startFinger();
//                        } else {
//                            mFingerUtil.startControl();
//                        }
                    }
                }
            }
        } else {// 全封包模式
            if (!app.user.getName().equals(user.getName())) {

                showToastUtils.showBigToast("用户不一致请重新交接", Toast.LENGTH_LONG);
//                mFingerUtil.startControl();
            } else {
                if ("".equals(tv_sign5.getText().toString()) || tv_sign5.getText().toString() == null) {
                    if (user.getUserId().equals(Constant.YyRoleId)) {// 押运人员登录
                        userid = userId + "_";
                        tv_sign5.setText(user.getName());// 验证成功后在相应的地方显示用户名

                        iv_sign5.setImageBitmap(null);
                        iv_sign5.setBackgroundResource(R.drawable.sccuss);
                        if (plist.size() == 1) {
                            tv_sign1.setEnabled(true);
                            tv_sign1.setText(plist.get(0).getName());
                            qianmingLayout.setVisibility(View.GONE);
                        } else if (plist.size() == 2) {
                            tv_sign1.setEnabled(true);
                            tv_sign2.setEnabled(true);// 用户名验证成功后可以进行签名
                            tv_sign1.setText(plist.get(0).getName());
                            tv_sign2.setText(plist.get(1).getName());
                            tv_sign1.setBackgroundColor(Color.parseColor("#4ec1fc"));
                            tv_sign2.setBackgroundColor(Color.parseColor("#4ec1fc"));
                        }
                        startjiaojie.setEnabled(false);
                        startjiaojie.setBackgroundResource(R.drawable.button_gray);
                    } else {
                        useDialog.setTitle("请用押运员登录");
                        showToastUtils.showBigToast("请使用押运员验证..", Toast.LENGTH_SHORT);
                    }
                }
            }
        }
    }
}





